package com.shareyi.wox.result;

import java.io.Writer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;

import com.shareyi.wox.context.ActionContext;
import com.shareyi.wox.context.ServletActionContext;
import com.shareyi.wox.context.ValueContext;
import com.shareyi.wox.core.ActionInvocation;
import com.shareyi.wox.core.WoxException;
import com.shareyi.simpleserver.core.HttpRequest;
import com.shareyi.simpleserver.core.HttpResponse;
import com.shareyi.simpleserver.core.SimpleHttpServer;

public class VelocityResult extends WoxResultSupport {

	
	private static final Log LOG = LogFactory.getLog(VelocityResult.class);
    protected boolean initialed;
  //  private String defaultEncoding;
	//初始化并取得Velocity引擎
	private VelocityEngine ve;
	
	public void init() throws WoxException {
		ve=new VelocityEngine();
		ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,SimpleHttpServer.getServerInstance().getBasePath());
		ve.setProperty(Velocity.INPUT_ENCODING,"utf-8");
		ve.setProperty(Velocity.OUTPUT_ENCODING,"utf-8");
		ve.init();
	}
	
	
    
	@Override
	protected void doExecute(String finalLocation, ActionInvocation invocation)
			throws Exception {
		if(!initialed){
			init();
			initialed=true;
		}
		
		   ValueContext valueContext = ActionContext.getContext().getValueContext();
	        HttpRequest request = ServletActionContext.getRequest();
	        HttpResponse response = ServletActionContext.getResponse();
	        try {
	            Template t = getTemplate(invocation, finalLocation);

	            Context context = createContext(valueContext, request, response, finalLocation);
	            Writer writer = response.getPrintWriter();
	            t.merge(context, writer);
	            writer.flush();
	        } catch (Exception e) {
	            if (LOG.isErrorEnabled()) {
	                LOG.error("Unable to render Velocity Template, '#0'", e);
	            }
	            throw e;
	        } finally {
	           
	        }
		
		
		

	}



	protected Template getTemplate(ActionInvocation invocation,
			String finalLocation) {
		
		return  ve.getTemplate(finalLocation);
	}



	protected Context createContext(ValueContext valueContext,
			HttpRequest request, HttpResponse response, String finalLocation) {
		   	VelocityContext context=new VelocityContext(valueContext.getContext());
			context.put("request",request);
			context.put("requestAttr", request.getAttributeMap());
			//context.put("response",response);
			return context;
	}

}
